import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/assets/images/profile.jpg";
import { timePanelSharedProps } from "element-plus/es/components/time-picker/src/props/shared";
const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
    userDta: {},
  }),
  actions: {
    // 登录
    login(userInfo) {
      const userName = userInfo.userName.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const status = userInfo.status;
      const phone = userInfo.phone;
      const verification = userInfo.verification;

      return new Promise((resolve, reject) => {
        login(userName, password, code, status, phone, verification)
          .then((res) => {
            setToken(res.data.id);
            this.token = res.data.id;
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo({ id: getToken() })
          .then((resD) => {
            this.userDta = resD.data;
            let res = {
              msg: "操作成功",
              code: 200,
              permissions: [],
              roles: [1],
              user: {},
              id: resD.data.id,
            };
            if (resD.data.permissions != null) {
              for (let i = 0; i < resD.data.permissions.length; i++) {
                res.permissions.push(resD.data.permissions[i].menuComponent);
              }
            } else {
              resolve("登录失败 你没有相关权限");
            }
            if (resD.data.ids == null) {
              resolve("登录失败 你还未创建仓库");
            }
            const user = res.user;
            this.roles = res.roles;
            this.permissions = res.permissions;
            this.name = user.userName;
            this.avatar = resD.data.image;
            resolve(res);
          })
          .catch((error) => {
            removeToken();
            reject(error);
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout()
          .then((res) => {
            this.token = "";
            this.roles = [];
            this.permissions = [];
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    toKid() {
      this.token = "";
      this.roles = [];
      this.permissions = [];
      removeToken();
      resolve();
    },
  },
});

export default useUserStore;
